package com.weng.platform.draw.api;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.weng.cloud.utils.CloudAuthUtil;
import com.weng.framework.core.model.ResponseData;
import com.weng.framework.web.base.BaseController;
import com.weng.platform.draw.entity.DrawData;
import com.weng.platform.draw.service.IDrawDataService;
import com.weng.platform.draw.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *  画布文件数据操作--主要给io-draw使用
 */
@RestController
@RequestMapping("/draw-data")
@Slf4j
public class DrawDataApi extends BaseController {

		@Autowired
		private IDrawDataService drawDataService;

		/**
     *
     * @param uuid
     * @param request
     * @param response
     * @throws IOException
     */
    @GetMapping("/get/{uuid}")
    @ResponseBody
    public void get(@PathVariable String uuid, HttpServletRequest request, HttpServletResponse response) throws IOException {

        //获取内容
				DrawData drawData = drawDataService.getById(uuid);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", drawData.getName());
        jsonObject.put("data", new String(drawData.getBody()));
        response.getOutputStream().write(jsonObject.toJSONString().getBytes());
        response.setStatus(200);
    }


    @PostMapping("/save")
    @ResponseBody
    public void save(HttpServletRequest request, HttpServletResponse response) throws IOException {

        try {
            String drawJsonStr = HttpUtil.getBodyString(request);
            JSONObject drawJson = JSONObject.parseObject(drawJsonStr);
            log.info("save File:{}", drawJson);
            String id = drawJson.getString("id");
            String ownerId = CloudAuthUtil.getCurUserId(request);
            String ownerName = CloudAuthUtil.getCurUserTrueName(request);
            String title = drawJson.getString("title");
            String data = drawJson.getString("data");
            DrawData drawData = drawDataService.getById(id);
            // 权限验证,因为token在iodraw中无法传，所以无法获取
//						if(StringUtils.isNullOrEmpty(ownerId)  || StringUtils.isNullOrEmpty(data) ||
//										StringUtils.isNullOrEmpty(title) || !ownerId.equals(drawData.getOwnerId())){
//								response.setStatus(403);
//								return;
//						}
            if (drawData == null){
                drawData = new DrawData();
								drawData.setId(id);
								drawData.setOwnerId(ownerId);
								drawData.setOwnerName(ownerName);

								drawData.setName(title);
								drawData.setBody(data.getBytes());
								drawDataService.save(drawData);
            }else{
								drawData.setName(title);
								drawData.setBody(data.getBytes());
								drawDataService.update(drawData);
						}
            log.info("save File:{}", JSONObject.toJSONString(drawData));
            response.setStatus(200);
        } catch (Exception e){
            response.setStatus(400);
            log.error("save error:{}", e.getMessage());
        }
    }


    @GetMapping("/list")
    @ResponseBody
    public ResponseData get(HttpServletRequest request, String name, Integer pageNo,Integer pageSize, String columnId,Boolean isQueryChild ) throws IOException {
        String ownerId = CloudAuthUtil.getCurUserId(request);
				IPage<DrawData> iPage = drawDataService.list(pageNo, pageSize, ownerId, name, columnId, isQueryChild);
				return success(iPage);
    }

    @RequestMapping(value = "/del/{ids}", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject delAllByIds(@PathVariable String[] ids) {
        JSONObject jsonObject = new JSONObject();
        for (String id: ids) {
						drawDataService.removeById(id);
        }
        jsonObject.put("code", "200");
        return jsonObject;
    }
}
